<template>
  <q-dialog v-model="visible">
    <modify-order ref="newOrderDetail" @refresh="getOrders"/>
    <modify-order ref="modifyOrderDetail" @refresh="getOrders" modify/>
    <order-detail-uploader ref="excelUploader" @load="getOrders"/>
    <q-card style="max-height: calc(100vh - 2rem); max-width: 90vw">
      <q-tab-panels
          v-model="panel"
          animated
          infinite
          class="overflow-x-hidden"
          style="max-height: calc(100vh - 10rem); overflow-y: auto"
      >
        <q-tab-panel name="orderDetails" class="q-pa-none">
          <q-card-section class="flex q-gutter-x-sm items-center">
            <div class="text-h6">任务内订单</div>
            <q-space/>
            <q-btn color="primary" label="新增订单" icon="playlist_add" @click="newOrderDetail.show(task.id)"/>
            <q-btn icon="unarchive" color="secondary" @click="excelUploader.show(task.id)" label="批量上传"/>
            <q-btn-group class="q-pa-none row">
              <q-btn v-show="task.status === '未开始'" color="primary" class="col" label="立即执行" @click="execute"/>
              <q-btn color="negative" class="col" label="删除任务" @click="remove"/>
            </q-btn-group>
          </q-card-section>
          <q-separator/>
          <q-table
              :card-container-style="{ 'overflow': 'auto' }"
              card-container-class="justify-center q-pa-sm"
              grid
              :rows="orderList"
              row-key="id"
              virtual-scroll
              :rows-per-page-options="[0]"
              :virtual-scroll-sticky-size-start="48"
              hide-header
          >
            <template v-slot:item="props">
              <q-card class="q-ma-sm" @click="modifyOrderDetail.show(props.row)">
                <q-card-section class="text-subtitle1 text-bold">优先度 {{ props.row.priority }}</q-card-section>
                <q-separator/>
                <q-list dense>
                  <q-item dense v-for="item in param" v-bind:key="item.key" clickable v-ripple>
                    <q-item-section side>{{ item.label }}</q-item-section>
                    <q-item-section class="text-right">{{ props.row[item.value] || '无' }}</q-item-section>
                  </q-item>
                  <template v-if="props.row.type === 'transport-lift'">
                    <map-pose-info center :pose-id="props.row.startPose" label="取货工位"/>
                    <map-pose-info center :pose-id="props.row.targetPose" label="送货工位"/>
                  </template>
                </q-list>
              </q-card>
            </template>
            <template v-slot:no-data>
              <div class="full-width row flex-center q-gutter-sm q-pb-xl text-h6 text-grey-7 content-center">
                <q-icon size="5rem" name="sentiment_dissatisfied"/>
                <div class="text-center full-width">
                  当前任务中还没有订单
                </div>
              </div>
            </template>
          </q-table>
        </q-tab-panel>

        <q-tab-panel name="modify" class="q-pa-none">
          <q-card-section class="text-h6 flex items-center q-gutter-x-sm">
            <div>修改任务</div>
            <transition-flip>
              <q-btn-group class="q-pa-none row" v-if="modified">
                <q-btn color="primary" class="col" label="修改任务" @click="update"/>
                <q-btn color="secondary" class="col" label="还原修改" @click="reset"/>
              </q-btn-group>
              <q-btn-group class="q-pa-none row" v-else>
                <q-btn v-show="task.status === '未开始'" color="primary" class="col" label="立即执行" @click="execute"/>
                <q-btn color="negative" class="col" label="删除任务" @click="remove"/>
              </q-btn-group>
            </transition-flip>
          </q-card-section>
          <q-separator/>
          <q-card-section class="q-gutter-y-sm">
            <q-input outlined label="任务ID" readonly v-model="task.id"/>
            <q-input outlined label="状态" readonly v-model="task.status"/>
            <amr-selector outlined v-model="task.device"/>
            <q-input rows="3" v-model="task.description" filled type="textarea"
                     placeholder="在此输入对于任务的一些描述"/>
          </q-card-section>
        </q-tab-panel>
      </q-tab-panels>
      <q-tabs
          v-model="panel"
          dense
          class="bg-grey-3"
          align="justify"
          narrow-indicator
      >
        <q-tab name="orderDetails" label="订单列表"/>
        <q-tab name="modify" label="修改任务"/>
      </q-tabs>
    </q-card>
  </q-dialog>
</template>

<script>
import {useQuasar} from 'quasar'
import {computed, onMounted, ref} from 'vue'
import {useAPIStore} from 'stores/api'
import {api} from 'boot/axios'

import OrderDetailUploader from 'components/transport/orders/OrderUploader.vue'
import ModifyOrder from 'components/transport/orders/ModifyOrder.vue'
import amrSelector from 'components/actionPlan/AmrSelector.vue'
import MapPoseInfo from 'components/amr/MapPoseInfo.vue'
import TransitionFlip from 'components/animations/Flip.vue'

const param = [
  {label: '订单状态', value: 'status'},
  {label: '创建时间', value: 'createTime'}
]

export default {
  name: 'ModifyTask',
  components: {TransitionFlip, MapPoseInfo, amrSelector, ModifyOrder, OrderDetailUploader},
  setup(props, context) {
    const $q = useQuasar()
    const visible = ref(false)

    const origin = ref({})
    const task = ref({
      id: '',
      sender: '',
      description: '',
      device: ''
    })
    const orderList = ref([])

    function getOrders() {
      api.get(useAPIStore().orderUrl + 'order/task/' + task.value.id).then(rs => {
        orderList.value = rs.data
      })
    }

    const devices = ref([])

    function getDevices() {
      api.get(useAPIStore().centerUrl + 'configs/all').then(rs => {
        devices.value = rs.data.map((item) => {
          return item.id
        })
      })
    }

    onMounted(getDevices)

    return {
      visible,
      panel: ref('orderDetails'),
      param,
      task,
      orderList,
      devices,
      modified: computed(() => JSON.stringify(origin.value) !== JSON.stringify(task.value)),
      newOrderDetail: ref(),
      modifyOrderDetail: ref(),
      excelUploader: ref(),
      getOrders,
      show(data) {
        origin.value = data
        task.value = JSON.parse(JSON.stringify(data))
        getOrders()
        visible.value = true
      },
      update() {
        api.put(useAPIStore().orderUrl + 'task', task.value).then(rs => {
          if (rs.data === 'modified') {
            $q.notify({type: 'positive', message: '任务修改成功'})
            context.emit('refresh')
            visible.value = false
          }
        })
      },
      reset() {
        task.value = JSON.parse(JSON.stringify(origin.value))
      },
      remove() {
        $q.dialog({
          title: '删除任务',
          message: '是否要删除该运输任务？',
          cancel: true,
          persistent: true
        }).onOk(() => {
          api.delete(useAPIStore().orderUrl + 'task/' + task.value.id).then(rs => {
            $q.notify({type: 'positive', message: '订单删除成功'})
            context.emit('refresh')
            visible.value = false
          })
        })
      },
      execute() {
        $q.dialog({
          title: '执行任务',
          message: '是否要立即执行该运输任务？',
          cancel: true,
          persistent: true
        }).onOk(() => {
          api.post(useAPIStore().centerUrl + 'center/send/' + task.value.device, {content: task.value.id, type: 'task'})
              .then(res => {
                console.log('-------', res)
                if (res.data === 'done') {
                  $q.notify({type: "positive", message: "指令下发成功"});
                } else {
                  $q.notify({type: "negative", message: "指令下发失败：" + res.data});
                }
              }).catch(err => {
            $q.notify({type: "negative", message: "指令下发失败：" + err.message});
          })
        })
      }
    }
  }
}
</script>
